import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { finalize } from 'rxjs';

import { RequestParams } from '@app/core/domain/request-params';
import { OperationService } from '@app/core/services/http/operation/operation.service';
import { ScanRecord, ScanRecordService } from '@app/core/services/http/scan-record/scan-record.service';
import { AntTableComponent, AntTableConfig, SortFile } from '@app/shared/components/ant-table/ant-table.component';
import { CardTableWrapComponent } from '@app/shared/components/card-table-wrap/card-table-wrap.component';
import { PageHeaderComponent, PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { WaterMarkComponent } from '@app/shared/components/water-mark/water-mark.component';
import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzImageModule } from 'ng-zorro-antd/image';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageModule, NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzSwitchModule } from 'ng-zorro-antd/switch';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

import { MatchResultModalComponent } from './match-result-modal/match-result-modal.component';
import { MatchResultModalService } from './match-result-modal/match-result-modal.service';

@Component({
  selector: 'app-login-log',
  standalone: true,
  imports: [
    NzMessageModule,
    PageHeaderComponent,
    FormsModule,
    NzFormModule,
    NzGridModule,
    NzInputModule,
    NzButtonModule,
    NzIconModule,
    CardTableWrapComponent,
    AntTableComponent,
    CommonModule,
    NzPopconfirmModule,
    NzBadgeModule,
    NzSpaceModule,
    NzCardModule,
    WaterMarkComponent,
    NzSwitchModule,
    NzImageModule,
    NzSelectModule
  ],
  templateUrl: './scan-log.component.html',
  styleUrl: './scan-log.component.less'
})
export class ScanLogComponent implements OnInit {
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('userAvatar', { static: true }) avatar!: TemplateRef<NzSafeAny>;
  pageSearchParam: NzSafeAny = { imageName: '', imageContent: '' };
  tableConfig!: AntTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '识别日志',
    breadcrumb: ['首页', '系统日志', '识别日志']
  };
  isCollapse: boolean = true;

  scanLogs: ScanRecord[] = [];
  checkedCashArray: NzSafeAny[] = [];
  private readonly destroyRef = inject(DestroyRef);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly scanRecordService: ScanRecordService = inject(ScanRecordService);
  private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef);
  private readonly operationService: OperationService = inject(OperationService);
  private readonly modalService: MatchResultModalService = inject(MatchResultModalService);

  private initTable(): void {
    this.tableConfig = {
      headers: [
        {
          title: '用户名',
          width: 130,
          field: 'username',
          show: true,
          showSort: false
        },
        {
          title: '图片名称',
          width: 130,
          field: 'imagename',
          show: true,
          showSort: false
        },
        {
          title: '图片内容',
          width: 130,
          field: 'imagecontent',
          show: true,
          showSort: false
        },
        {
          title: '图片',
          width: 130,
          field: 'imageurl',
          show: true,
          showSort: false,
          tdTemplate: this.avatar
        },
        {
          title: '上传时间',
          width: 130,
          field: 'addtime',
          show: true,
          showSort: false
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 120,
          fixed: true,
          fixedDir: 'right'
        }
      ],
      total: 0,
      showCheckbox: false,
      loading: false,
      pageSize: 10,
      pageIndex: 1
    };
  }

  selectedChecked(e: NzSafeAny): void {
    this.checkedCashArray = [...e];
  }

  resetForm(): void {
    this.pageSearchParam = {};
    this.search();
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

  reloadTable(): void {
    this.messageService.info('已经刷新了');
    this.getScanLogs();
  }

  tableChangeDectction(): void {
    this.scanLogs = [...this.scanLogs];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  appendRequestParams(): RequestParams {
    const filter: Partial<ScanRecord> = {};
    let requestParams: RequestParams = {
      '@relationships': 'UserInfo',
      current: this.tableConfig.pageIndex,
      pageSize: this.tableConfig.pageSize,
      '@filter': '',
      ...filter
    };

    if (this.pageSearchParam.Name) {
      requestParams['@filter'] += `contains(ImageName,${this.pageSearchParam.Name})`;
    }

    if (this.pageSearchParam.imageContent) {
      const option = this.pageSearchParam.imageContent === '0' ? 'isnull' : 'isnotnull';
      requestParams['@filter'] += `${option}(ImageContent)`;
    }

    return requestParams;
  }

  getScanLogs(e?: NzTableQueryParams): void {
    if (e) {
      this.tableConfig.pageIndex = e?.pageIndex;
    }
    this.checkedCashArray = [...this.checkedCashArray];
    this.tableConfig.loading = true;
    let requestParams: RequestParams = this.appendRequestParams();

    this.scanRecordService
      .getEntityPageList(requestParams)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(students => {
        const { records, total } = students;
        this.scanLogs = records;
        this.tableConfig.total = total;
      });
  }

  changeSort(e: SortFile): void {
    //e.fileName , e.sortDir
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getScanLogs();
  }

  previewImage(id: number): void {
    this.scanRecordService
      .getEntityById(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(scanRecord => {
        const imageContent = scanRecord[0].imagecontent;
        if (imageContent) {
          this.messageService.info(`图片内容: ${imageContent}`);
        } else {
          this.messageService.warning('没有图片内容可预览');
        }
      });
  }

  matchResult(id: number): void {
    this.operationService
      .getCardInfos(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(cardInfos => {
        this.modalService.show({ nzTitle: '匹配结果' }, cardInfos);
      });
  }

  ngOnInit(): void {
    this.initTable();
  }
}
